package com.hhu.softpractise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhu.softpractise.common.ErrorCode;
import com.hhu.softpractise.exception.BusinessException;
import com.hhu.softpractise.exception.ThrowUtils;
import com.hhu.softpractise.model.entiy.Post;
import com.hhu.softpractise.model.entiy.PostThumb;
import com.hhu.softpractise.model.entiy.User;
import com.hhu.softpractise.service.PostService;
import com.hhu.softpractise.service.PostThumbService;
import com.hhu.softpractise.mapper.PostThumbMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @author 35534
* @description 针对表【post_thumb(帖子点赞)】的数据库操作Service实现
* @createDate 2025-06-23 14:16:35
*/
@Service
public class PostThumbServiceImpl extends ServiceImpl<PostThumbMapper, PostThumb>
    implements PostThumbService{


    @Resource
    private PostService postService;

    /**
     * 帖子点赞
     *
     * @param postId 帖子 id
     * @param loginUser 登录用户
     * @return
     */
    @Override
    public int doPostThumb(long postId, User loginUser) {
        //找到帖子
        Post post = postService.getById(postId);
        ThrowUtils.throwIf(post == null, ErrorCode.NOT_FOUND_ERROR);
        //判断当前登录用户是否已点赞
        long userId = loginUser.getId();
        synchronized (String.valueOf(userId).intern()) {
            return this.doPostThumbInner(userId, postId);
        }
    }

    @Override
    public int doPostThumbInner(long userId, long postId) {
        QueryWrapper<PostThumb> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("postId", postId);
        queryWrapper.eq("userId", userId);
        PostThumb oldPostThumb = this.getOne(queryWrapper);
        if(oldPostThumb != null) {
            //删除
            boolean remove = this.remove(queryWrapper);
            if(remove) {
                //帖子点赞数-1
                Post post = postService.getById(postId);
                post.setThumbNum(post.getThumbNum() - 1);
                boolean update = postService.updateById(post);
                return update ? -1 : 0;
            }else{
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }else{
            //添加
            PostThumb postThumb = new PostThumb();
            postThumb.setPostId(postId);
            postThumb.setUserId(userId);
            boolean save = this.save(postThumb);
            if(save) {
                //帖子点赞数+1
                Post post = postService.getById(postId);
                post.setThumbNum(post.getThumbNum() + 1);
                boolean update = postService.updateById(post);
                return update ? 1 : 0;
            }else{
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
    }
}




